<?php

namespace app\common\model\banxi\sys;

use app\common\enums\core\BusinessStatusEnum;
use app\common\enums\core\UserTypeEnum;
use app\common\model\common\BaseModel;
use app\common\service\UserAgentParserService;

/**
 * Admin模型
 * @property int $id              管理员ID
 * @property string $username        管理员用户名
 * @property string $nickname        管理员昵称
 * @property string $email           管理员邮箱
 * @property string $mobile          管理员手机号
 * @property string $last_login_ip   上次登录IP
 * @property string $last_login_time 上次登录时间
 * @property int $login_failure   登录失败次数
 * @property string $password        密码密文
 * @property string $salt            密码盐（废弃待删）
 * @property string $status          状态:enable=启用,disable=禁用,...(string存储，可自定义其他)
 */
class SysLogininfor extends BaseModel
{

    protected $name = 'banxi_sys_logininfor';
    /**
     * @var string 自动写入时间戳
     */
    protected $autoWriteTimestamp = true;

    protected $append = [
        'userTypeCn',
        'statusCn'
    ];

    protected $type = [
        'id' => 'string',
        'createTime' => 'timestamp:Y-m-d H:i:s',
        'updateTime' => 'timestamp:Y-m-d H:i:s',
    ];


    /**
     * 登录成功
     */
    public const LOGIN_SUCCESS = 'Success';
    /**
     * 注销
     */
    public const LOGOUT = 'Logout';
    /**
     * 注册
     */
    public const REGISTER = 'Register';
    /**
     * 登录失败
     */
    public const LONGIN_FAIl = 'Error';


    //-----------------------------------------------------------------------------------
    //｜                                   获取器                                       ｜
    //-----------------------------------------------------------------------------------

    public function getUserTypeCnAttr($value, $data)
    {
        $value = $value ?: ($data['userType'] ?? '');
        return (new UserTypeEnum())->getDescription($value) ?? '';
    }

    public function getStatusCnAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        return (new BusinessStatusEnum())->getDescription($value) ?? '';
    }

    //-----------------------------------------------------------------------------------
    //｜                                   处理方法                                       ｜
    //-----------------------------------------------------------------------------------

    public function recordLogininfor($userId, $username, $userType, $status, $message)
    {
        $request = request();
        $userAgent = $request->header()['user-agent'];
        $userAgentParserService = new UserAgentParserService();
        $os = $userAgentParserService->getOsName($userAgent);
        $browser = $userAgentParserService->getBrowserName($userAgent);
        $ip = $request->ip();
        $ipaddress = getRealAddressByIp($ip);
        $sys = new SysLogininfor();
        $sys->userId = $userId;
        $sys->userName = $username;
        $sys->userType = $userType;
        $sys->ipaddr = $ip;
        $sys->loginLocation = $ipaddress;
        $sys->browser = $browser;
        $sys->os = $os;
        $sys->msg = $message;
        $sys->loginTime = date('Y-m-d H:i:s');
        if (in_array($status, [SysLogininfor::LOGIN_SUCCESS, SysLogininfor::LOGOUT, SysLogininfor::REGISTER])) {
            $sys->status = BusinessStatusEnum::SUCCESS;
        } else if ($status == SysLogininfor::LONGIN_FAIl) {
            $sys->status = BusinessStatusEnum::FAIL;
        }
        $sys->save();
    }


}